package com.hmdp.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.CACHE_SHOP_TTL;
import static com.hmdp.utils.RedisConstants.CACHE_SHOP_TYPE_KEY;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    final private StringRedisTemplate stringRedisTemplate;
    @Override
    public Result queryTypeList() {
        String key = CACHE_SHOP_TYPE_KEY;
        //1、查询redis中的是否缓存商铺
        String shopTypeJson = stringRedisTemplate.opsForValue().get(key);

        if (StrUtil.isNotBlank(shopTypeJson)) {
        //2、如果存在，则直接返回
            log.info("成功从缓存中查询到商铺类型信息！");
            List<ShopType> shopTypeList = JSONUtil.toList(shopTypeJson, ShopType.class);
            return Result.ok(shopTypeList);
        }
        //3、不存在，去数据库中查询
        List<ShopType> shopTypeList = list();
        //4、数据库中不存在，返回错误
        if(shopTypeList == null || shopTypeList.isEmpty()){
            return Result.fail("不能存在商铺类型");
        }
        //5、数据库中存在，将查询到的数据存入Redis中
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(shopTypeList),CACHE_SHOP_TTL, TimeUnit.MINUTES);
        //6、返回
        return Result.ok(shopTypeList);
    }
}
